--[[
FilePath: \Lua\View\UIActivityLuckyGuy\UIActivityLuckyGuy.lua
转盘活动
--]]

require 'View/UIBase/UIBase'
local TaskItem = require "View/UIActivityLuckyGuy/TaskItem"
local RankItem = require "View/UIActivityLuckyGuy/RankItem"
local RechargeItem = require "View/UIActivityLuckyGuy/RechargeItem"

UIActivityLuckyGuy = UIBase.New(PanelNames.UIActivityLuckyGuy)
local _M = UIActivityLuckyGuy

_M.hasInit = false
_M.rechargeItem = nil;
_M.taskItem = nil;
_M.rankItem = nil;
_M.spineAnim = nil;
_M.particleSystem = nil;
_M.selectIndex = 1;
_M.updateTimer = nil;
_M.idleTimer = nil;
_M.curRotation = 0;
_M.preRotation = 0;
_M.acSpeed = 3; -- 加速度
_M.acTime = 20; -- 加速运动时间
_M.acDis = 0;
_M.speed = 0;
_M.speedTime = 0;
_M.reSpeed = 1; -- 减速度
_M.reTime = 60; -- 减速带时间
_M.reDis = 0;
_M.reSpeedTime = 0; -- 速带时间
_M.reSpeedDic = 0; -- 速带距离
_M.spTime = 0;
_M.curRewardIndex = 1;
_M.spCount = 0;
_M.rewardRotation = 45;
_M.serverReward = nil;
_M.hasInitRewardItem = false;
_M.activityType = 0;
_M.resetRewardCost = 0;
_M.isClick = false;
_M.drawType = 0;
_M.lastDrawType = 0;

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Backbtn"), self.OnClose)
        self.name = self:GetChild("title"):GetChild("title");
        self.CoinLb = self:GetChild("CoinLb");
        self.CoinLb1 = self:GetChild("CoinLb1");
        self.typeCtrl = self:GetController("Type");
        self.typeCtrl.selectedIndex = 0;
        self.banner = self:GetChild("HeroBgIcon");
        self.lihui = self:GetChild("lihui");
        self.effect = self:GetChild("eff_zhuanquan");
        self.maskCtrl = self:GetController("mask");
        self.maskCtrl.selectedIndex = 1;
        self.btnHelp = self:GetChild("help");

        self.actTime = self:GetChild("bannerText1");
        self.endTime = self:GetChild("bannerText2");
        self.score = self:GetChild("bannerscoer");
        self.rankTips1 = self:GetChild("rank1tips");
        self.rankTips2 = self:GetChild("rank2tips");
        self.btnDrawOne = self:GetChild("btndraw1");
        self.costIcon1 = self.btnDrawOne:GetChild("cost");
        self.txtCost1 = self.btnDrawOne:GetChild("num1");
        self.btnDrawTen = self:GetChild("btndraw10");
        self.costIcon2 = self.btnDrawTen:GetChild("cost");
        self.txtCost2 = self.btnDrawTen:GetChild("num1");
        self.btnShop = self:GetChild("ShopBtn");
        self.showTips = self:GetChild("Tips1");
        self.freeCtrl = self:GetController("isfree");
        self.freeCtrl.selectedIndex = 0;
        self.btnDrawFree = self:GetChild("btndrawfree");
        self.txtFree = self.btnDrawFree:GetChild("title");

        self.btnSignExt = {};
        for i = 2, 2 do
            table.insert(self.btnSignExt, self:GetChild("btnSign1_"..i));
        end
        self.btnShowCtrl = self:GetController("BtnShow");
        self.btnShowCtrl.selectedIndex = 0;
        self.refreshRewardCost = self:GetChild("Cost");
        self.btnSignCtrl = self:GetController("btnSign");

        -- 转盘
        local luckyGuy = self:GetChild("UILuckyGuy");
        self.bgZhiZhen = luckyGuy:GetChild("bgzhizhen");
        self.selectIndex = -1
        local effectCtrl = luckyGuy:GetController("IsShow");
        effectCtrl.selectedIndex = 1;
        self.bgLight = luckyGuy:GetChild("bglight");
        self.bgLight.visible = false;
        self.bgTran = luckyGuy:GetTransition("bglight");

        -- 烟花
        local fireWorks = self:GetChild("UILuckyFireWorks");
        self.fireItemList = {};
        self.fireItemCtrl = {};
        for i = 1, 8 do
            local fireItem = fireWorks:GetChild("item"..i);
            table.insert(self.fireItemList, fireItem:GetChild("n3"));
            table.insert(self.fireItemCtrl, fireItem:GetController("ItemType"));
        end
        self.eff_yanhua1 = self:GetChild("eff_yanhua_1");
        self.eff_yanhua10 = self:GetChild("eff_yanhua_10");

        self.taskRedCtrl = self:GetChild("btnSign3"):GetChild("UIRedDots"):GetController("c1");
        self.rechargeRedCtrl = self:GetChild("btnSign2"):GetChild("UIRedDots"):GetController("c1");
        self.dailyTaskRedCtrl = self:GetChild("btnSign6"):GetChild("UIRedDots"):GetController("c1");
        self.rankRedCtrl = self:GetChild("btnSign5"):GetChild("UIRedDots"):GetController("c1");
        self.btnMaskCtrl = self:GetController("BtnMask");
        self.btnMaskCtrl.selectedIndex = 0;
        self.btnSignMask = self:GetChild("btnSign1mask");
        self.btnSignMask.visible = false;
        self.btnSign = {};
        for i = 1, 6 do
            table.insert(self.btnSign, self:GetChild("btnSign"..i));
        end
        self.selectIndex = 1;
        self.itemList = {};
        for i = 1, 8 do
            table.insert(self.itemList, luckyGuy:GetChild("item"..i));
        end

        self.totalRecharge = self:GetChild("UITotalRecharge");
        self.luckyGuyTask = self:GetChild("UILuckyGuyTask");
        self.luckyGuyRank = self:GetChild("UILuckyGuyRank1");

        if self.activeId ~= nil then
            local activityTabConfig = G.dataTable["t_activitylist"][tostring(self.activeId)];
            self.activeConfigModel = dataTable.getDataTableByStringId(activityTabConfig.f_ModelName,self.activeId)
            self.tableDataCfg = dataTable.getDataTableByStringId(self.activeConfigModel.f_ItemTableName,self.activeId)
        end

        self:initView();
        _M.hasInit = true;
        self:addEvent();
        --ActivityHandler.sendReqTurntableActivityInfoMessage(EnumConst.ActivityId.Turntable);
       -- ActivityHandler.sendReqTurntableTaskListInfoMessage(EnumConst.ActivityId.Turntable);
    end
end

function _M:addEvent()
    self:RegisterEvent(Config.EventType.Fresh_Active,self.RefreshView);
    self:RegisterEvent(Config.EventType.Fresh_TurntableActivityAwardPool,self.RefreshAwardPool);
    self.btnHelp.onClick:Add(self.HelpTip, self)
    self.btnShop.onClick:Add(self.BtnShop, self)
    self.btnDrawOne.onClick:Add(self.drawOne, self)
    self.btnDrawFree.onClick:Add(self.drawFree, self)
    self.btnDrawTen.onClick:Add(self.drawTen, self)
    for i = 1, #self.btnSign do
        local index = i;
        self.btnSign[index].onClick:Add(function()
            self:onClickBtn(index);
        end)
    end
    self.btnSignMask.onClick:Add(function()
        UISysTips.AddMsg(getLanguage("ActivityTips19001007"));
    end);
    for i = 1, #self.btnSignExt do
        local extIndex = i;
        self.btnSignExt[extIndex].onClick:Add(function()
            self:onClickBtn((6 + extIndex));
        end);
    end
end

function _M:removeEvent()
    self.btnHelp.onClick:Remove(self.HelpTip)
    self.btnShop.onClick:Remove(self.BtnShop)
    self.btnDrawOne.onClick:Remove(self.drawOne)
    self.btnDrawFree.onClick:Remove(self.drawFree)
    self.btnDrawTen.onClick:Remove(self.drawTen)
    for i = 1, #self.btnSign do
        local index = i;
        self.btnSign[index].onClick:Clear();
    end
    self.btnSignMask.onClick:Clear();
    for i = 1, #self.btnSignExt do
        local extIndex = i;
        self.btnSignExt[extIndex].onClick:Clear();
    end
end

function _M:HelpTip()
    if self.activeConfigModel ~= nil and self.activeConfigModel.f_ExplainTitle ~= nil and self.activeConfigModel.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(self.activeConfigModel.f_ExplainTitle), tostring(self.activeConfigModel.f_ExplainText));
    end
end

function _M:BtnShop()
    -- 刷新奖励
    if self.isClick then
        return;
    end
    if logicMgr.ItemManager.getBagNumByTableID("1") < self.resetRewardCost then
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"), logicMgr.ItemManager.GetItemName("1")));
    else
        self.isClick = true;
        local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
        pop.Init(125, function (flag)
            if flag then
                ActivityHandler.sendReqResetAwardPool(self.activeId);
            else
                self.isClick = false;
            end
        end, self.resetRewardCost);
    end
end

function _M:drawOne()
    if self.challengeTimeCountDown <= 0 then
        UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"));
        return;
    end

    if self.itemName1 ~= nil then
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),self.itemName1));
        return;
    end
    self.maskCtrl.selectedIndex = 0;
    self.drawType = 1;
    if self.activityType == 0 then
        AudioManager.Play(4018);
    elseif self.activityType == 6 then
        AudioManager.Play(4023);
    end
    ActivityHandler.sendReqTurntableAwardMessage(_M.activeId, 1);
end

function _M:drawFree()
    if self.challengeTimeCountDown <= 0 then
        UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"));
        return;
    end
    self.maskCtrl.selectedIndex = 0;
    self.drawType = 1;
    if self.activityType == 0 then
        AudioManager.Play(4018);
    elseif self.activityType == 6 then
        AudioManager.Play(4023);
    end
    ActivityHandler.sendReqTurntableAwardMessage(_M.activeId, 1);
end

function _M:drawTen()
    if self.challengeTimeCountDown <= 0 then
        UISysTips.AddMsg(getLanguage("Sys_ActivityEnd"));
        return;
    end
    if self.itemName2 ~= nil then
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),self.itemName2));
        return;
    end
    self.maskCtrl.selectedIndex = 0;
    self.drawType = 10;
    if self.activityType == 0 then
        AudioManager.Play(4018);
    elseif self.activityType == 6 then
        AudioManager.Play(4023);
    end
    ActivityHandler.sendReqTurntableAwardMessage(_M.activeId, 10);
end

function _M.onGetReward(rewardIndex, reward)
    _M.serverReward = reward;
    if _M.activityType == 0 then
        _M.bgLight.visible = false;
        _M:startTurntable(rewardIndex);
        if _M.spineAnim ~= nil then
            _M.spineAnim.AnimationState:SetAnimation(0, "idle2", false);
            local idleAniTime = _M.spineAnim.AnimationState.Data.SkeletonData:FindAnimation("idle2").Duration;
            if _M.idleTimer == nil then
                _M.idleTimer = Timer.New(_M.delayIdle, idleAniTime, 1, false);
            else
                _M.idleTimer:Reset(_M.delayIdle, idleAniTime, 1, false);
            end
            _M.idleTimer:Start();
        end
        _M.effect.visible = true;
    elseif _M.activityType == 6 then
        if _M.drawType == 1 then
            if _M.effectGo == nil then
                _M.effectGo, _M.effWrapper = _M:GetEffect("UI_yanhua_02", _M.eff_yanhua1)
            else
                _M.eff_yanhua1.visible = false;
                _M.eff_yanhua1.visible = true;
            end
        elseif _M.drawType == 10 then
            if _M.effectGo1 == nil then
                _M.effectGo1, _M.effWrapper1 = _M:GetEffect("UI_yanhua_03", _M.eff_yanhua10)
            else
                _M.eff_yanhua10.visible = false;
                _M.eff_yanhua10.visible = true;
            end
        end
        _M:DestroyRewardTimer();
        _M.rewardTimerId = utimer.timeCall(function()
            _M:showReward();
            _M.maskCtrl.selectedIndex = 1;
        end, 2500, 1);
    end
end

function _M:GetEffect(name, node)
    local effWrapper = GoWrapper.New();
    local effectGo = nil;
    resMgr:LoadModelPrefab("UIEff/"..name, function(go)
        if (effectGo ~= nil) then
            destroyImmediate(effectGo);
        end
        effectGo = newObject(go);
        effectGo.name = "zhuanpaneff"..name;
        effectGo:AddComponent(TCanvas);
        effWrapper:SetWrapTarget(effectGo, false);
        Util.Lua_SetLocalPositionXYZ(effectGo.transform, 0, 0, 0);
        Util.Lua_SetLocalScaleXYZ(effectGo.transform, 1, 1, 1);
        node:SetNativeObject(effWrapper);
    end)
    return effectGo, effWrapper;
end

function _M:delayIdle()
    -- 调用loop的idea
    if _M.spineAnim ~= nil then
        _M.spineAnim.AnimationState:SetAnimation(0, "idle1", true);
    end
end

function _M.onGetRewardFail()
    _M.maskCtrl.selectedIndex = 1;
end

function _M:startTurntable(rewardIndex)
    print("rewardIndex = "..rewardIndex);
    self.spTime = 0;
    self.reSpeedTime = 0;
    self.reSpeedDic = 0;
    local speedRotation = 0;
    if self.curRewardIndex == 1 then
        speedRotation = 360 * self.spCount + (rewardIndex - 1) * self.rewardRotation - self.acDis - self.reDis;
    else
        speedRotation = 360 * (self.spCount + 1) + (rewardIndex - 1) * self.rewardRotation - self.preRotation - self.acDis - self.reDis;
    end
    self.speedTime = speedRotation / self.speed;
    self.speedTotleTime = math.ceil(self.speedTime);
    self.curRewardIndex = rewardIndex;
    if self.updateTimer == nil then
        self.updateTimer = Timer.New(_M.onFrameRender, 0.033, -1, false);
    else
        self.updateTimer:Reset(_M.onFrameRender, 0.033, -1, false);
    end
    self.updateTimer:Start();
end

function _M.onFrameRender()
    _M.spTime = _M.spTime + 1;
    if _M.spTime <= _M.acTime then
        _M.curRotation = _M.preRotation + (_M.acSpeed * _M.spTime * _M.spTime) / 2;
    elseif _M.spTime <= (_M.acTime + _M.speedTotleTime) then
        local d = _M.acTime + _M.speedTime + 1 - _M.spTime;
        d = math.min(1, d);
        _M.curRotation = _M.curRotation + _M.speed * d;
    elseif _M.spTime <= (_M.acTime + _M.speedTotleTime + _M.reTime) then
        _M.reSpeedTime = _M.reSpeedTime + 1;
        local dic =  _M.speed * _M.reSpeedTime - (_M.reSpeed * _M.reSpeedTime * _M.reSpeedTime) / 2;
        _M.curRotation = _M.curRotation + dic - _M.reSpeedDic;
        _M.reSpeedDic = dic;
    else
        _M:DestroyTimer();
        _M.preRotation = _M.curRotation;
        _M.bgLight.rotation = _M.curRotation;
        _M.bgLight.visible = true;
        _M.bgTran:Play();
        _M:DestroyRewardTimer();
        _M.effect.visible = false;
        _M.rewardTimerId = utimer.timeCall(function()
            _M:showReward();
            _M.maskCtrl.selectedIndex = 1;
        end,500,1);
        return;
    end
    _M.curRotation = _M.curRotation % 360;
    _M.bgZhiZhen.rotation = _M.curRotation;
end

function _M:showReward()
    logicMgr.HeroManager.showNewHero(function ()
        if self.serverReward ~= nil then
            local rewards = {};
            for k,v in pairs(self.serverReward) do
                local itemData = logicMgr.CostManager.getItemOrEquipDataByIdAndNum(v.itemModelId, v.num);
                if itemData ~= nil then
                    table.insert(rewards, itemData);
                end
            end
            if #rewards > 0 then
                showUI(PanelNames.UICommonItemGet, nil, nil, 3, rewards, nil, nil, true);
            end
            self.serverReward = nil;
        end
    end);
end

-- 显示
function _M:OnEnable()
    self:Refresh(true);
    logicMgr.HeroManager.setGetNewHeroShow(true);
    logicMgr.ActiveManager.reqActivityExtendedData();
end

function _M:initView()
    self.speed = self.acSpeed * self.acTime;
    self.acDis = (self.acSpeed * self.acTime * self.acTime) / 2;
    self.reDis = (self.speed * self.speed) / (2 * self.reSpeed);
    self.spCount = math.ceil((self.acDis + self.reDis) / 360);
    self.bgZhiZhen.rotation = 0;

    if self.activeConfigModel ~= nil then
        if self.activeConfigModel.f_turnTableNum ~= nil and self.activeConfigModel.f_turnTableNum ~= "" then
            self.rewardRotation = 360 / tonumber(self.activeConfigModel.f_turnTableNum);
        end
        local nameIndex = tonumber(self.activeConfigModel.f_ActivityType) + 1;
        self.name.text = getLanguage("ActivityTips190010"..nameIndex);
        if self.activeConfigModel.f_BgPic ~= nil and self.activeConfigModel.f_BgPic ~= "" then
            self.banner.url = self.activeConfigModel.f_BgPic;
        end
        if self.activeConfigModel.f_ResourceShow ~= nil and self.activeConfigModel.f_ResourceShow ~= "" then
            local data = self.activeConfigModel.f_ResourceShow;
            if type(data) ~= "table" then
                data = decodeJsonStrToTabel(data);
            end
            self.itemId1 = data[1];
            self.itemId2 = data[2];
            local item = logicMgr.ItemManager.getItemConstDatabyModelId(self.itemId1);
            if item ~= nil then
                self.CoinLb.icon = EnumConst.AtlasPath.ItemAtlas..item.icon;
            end
            item = logicMgr.ItemManager.getItemConstDatabyModelId(self.itemId2);
            if item ~= nil then
                self.CoinLb1.icon = EnumConst.AtlasPath.ItemAtlas..item.icon;
            end
        end

        if self.activeConfigModel.f_Hero ~= nil then
            local imageName = logicMgr.HeroManager.GetHeroDrawingPath(self.activeConfigModel.f_Hero)
            if self.drawWrapper == nil then
                self.drawWrapper = GoWrapper.New()
            end
            resMgr:LoadModelPrefab(imageName, function(go)
                if(self.RoleLihui~=nil)then
                    destroyImmediate(self.RoleLihui);
                end
                self.RoleLihui = newObject(go);
                self.RoleLihui.name = imageName;
                Util.AddAction(self.RoleLihui,"idle1",true,0.5);
                self.RoleLihui:AddComponent(TCanvas);
                self.drawWrapper:SetWrapTarget(self.RoleLihui,false);
                Util.Lua_SetLocalPositionXYZ(self.RoleLihui.transform,0,0,0)
                Util.Lua_SetLocalScaleXYZ(self.RoleLihui.transform,1.1,1.1,1.1)
                self.lihui:SetNativeObject(self.drawWrapper);
                self.spineAnim = self.RoleLihui:GetComponent("SkeletonGraphic");
            end)
        end

        if self.activeConfigModel.f_ActivityType == 0 then
            if self.effWrapper == nil then
                self.effWrapper = GoWrapper.New();
            end
            resMgr:LoadModelPrefab("UIEff/UI_zhuanpan_01", function(go)
                if(self.effectGo~=nil)then
                    destroyImmediate(self.effectGo);
                end
                self.effectGo = newObject(go);
                self.effectGo.name = "zhuanpaneff";
                self.effectGo:AddComponent(TCanvas);
                self.effWrapper:SetWrapTarget(self.effectGo,false);
                Util.Lua_SetLocalPositionXYZ(self.effectGo.transform,0,0,0)
                Util.Lua_SetLocalScaleXYZ(self.effectGo.transform,1,1,1)
                self.effect:SetNativeObject(self.effWrapper);
                self.effect.visible = false;
                --self.particleSystem = self.effectGo:GetComponentInChildren("ParticleSystem");
                --if self.particleSystem ~= nil then
                --    self.particleSystem:Stop();
                --end
            end)
        end
    end
end

function _M:RefreshView()
    self:Refresh(false);
end

function _M:Refresh(showTime)
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
        return;
    else
        self.tableData, self.serverData, self.turntableInfo = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil or self.turntableInfo == nil then
            self:OnBack();
            return;
        end
    end
    if self.selectIndex == 1 or self.selectIndex == 7 then
        self:refreshCost();
    elseif self.selectIndex == 2 then
        if self.rechargeItem then
            self.rechargeItem.updateData(self.challengeTimeCountDown)
        end
        self:refreshTopCost();
    elseif self.selectIndex == 3 or self.selectIndex == 6 then
        if self.taskItem then
            local taskType = self.selectIndex == 3 and 1 or 2;
            self.taskItem.updateData(self.challengeTimeCountDown, taskType);
        end
        self:refreshTopCost();
    end
    self.taskRedCtrl.selectedIndex = self.serverData.taskRed;
    self.rechargeRedCtrl.selectedIndex = self.serverData.rechargeRed;
    self.dailyTaskRedCtrl.selectedIndex = self.serverData.dayTaskRed;
    local openState = logicMgr.ActiveManager.getActiveOpenStatus(self.activeId, 1);
    if openState ~= nil and openState then
        self.rankRedCtrl.selectedIndex = 2;
    else
        self.rankRedCtrl.selectedIndex = 0;
    end
    if showTime ~= nil and showTime then
        self.activityType = tonumber(self.tableData.f_ActivityType);
        self.typeCtrl.selectedIndex = self.activityType;
        self.btnSignCtrl.selectedPage = tostring(self.activityType);
        self.btnShowCtrl.selectedIndex = tonumber(self.tableData.f_ResetReward) == 0 and 0 or 1;

        local time = HelperFunc.GetServerTime();
        self.endCountDown = self.serverData.endTime - time;
        self.challengeTimeCountDown = self.endCountDown;
        local cfg = G.dataTable["t_activity"][tostring(self.activeId)];
        if cfg ~= nil and cfg.f_ChallengeTime ~= nil and tonumber(cfg.f_ChallengeTime) > 0 then
            self.challengeTimeCountDown = self.serverData.startTime + tonumber(cfg.f_ChallengeTime) - time;
        else
            if self.tableData.f_OutputTime ~= nil and self.tableData.f_OutputTime ~= "" and tonumber(self.tableData.f_OutputTime) > 0 then
                self.challengeTimeCountDown = self.serverData.startTime + tonumber(self.tableData.f_OutputTime) - time;
            end
        end
        if self.challengeTimeCountDown < -10 then
            self.typeCtrl.selectedIndex = 4;
            self.challengeTimeCountDown = -5;
            self:onClickBtn(5);
            self.btnMaskCtrl.selectedIndex = 1;
            self.btnSignMask.visible = true;
        end
        self:updateActiveCountDown();
        self:TimeCall(self.updateActiveCountDown, 1000, -1);
    end
    if not self.hasInitRewardItem then
        self.hasInitRewardItem = true;
        --初始化奖励
        self:resetReward();
    end
end

function _M:resetReward()
    local reward = {};
    local awardPool = self.turntableInfo.awardPool;
    for i = 1, #awardPool do
        local item = {};
        table.insert(item, awardPool[i].itemModelId);
        table.insert(item, tonumber(tostring(awardPool[i].num)));
        table.insert(item, awardPool[i].quality);
        table.insert(reward, item);
    end
    if self.activityType == 0 then
        for i = 1, #self.itemList do
            logicMgr.CostManager.RefreshItem(self.itemList[i], reward[i]);
        end
    elseif self.activityType == 6 then
        for i = 1, #self.fireItemList do
            local rewardItem = reward[i];
            logicMgr.CostManager.RefreshItem(self.fireItemList[i], rewardItem);
            self.fireItemCtrl[i].selectedIndex = rewardItem[3];
        end
    end
    local costArr = dataTable.getGlobalString(652);
    local costNum = #costArr;
    local resetCount = tonumber(self.turntableInfo.resetCount) + 1;
    if resetCount < 1 then
        resetCount = 1;
    elseif resetCount > costNum then
        resetCount = costNum;
    end
    self.resetRewardCost = tonumber(costArr[resetCount]);
    if logicMgr.ItemManager.getBagNumByTableID("1") < self.resetRewardCost then
        self.refreshRewardCost.text = string.format(getLanguage("ActivityTips19001009"), "[color=#FF2A4D]"..self.resetRewardCost.."[/color]");
    else
        self.refreshRewardCost.text = string.format(getLanguage("ActivityTips19001009"), "[color=#FFFFFF]" .. self.resetRewardCost .. "[/color]");
    end
    self.isClick = false;
end

function _M:RefreshAwardPool()
    local info = logicMgr.ActiveManager.GetTurntableActivityInfo(self.activeId);
    if info ~= nil then
        self.turntableInfo = info;
        self:resetReward();
    end
    self:refreshTopCost();
end

function _M:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    if self.endCountDown <= 0 then
        self.endTime.text =  getLanguage("Sys_ActivityEnd");
        self:RemoveTimeCall(self.updateActiveCountDown);
    else
        self.endTime.text = string.format(getLanguage("活动结束：", nil, "活动结束：%s"), HelperFunc.GetSurpTimeStr(self.endCountDown));
    end
    if self.challengeTimeCountDown > -20 then
        if self.challengeTimeCountDown <= 0 and self.challengeTimeCountDown > -10 then
            self.actTime.text = string.format(getLanguage("排行结算：", nil, "排行结算：%s"), getLanguage("ActivityTips19001007"));
            self.challengeTimeCountDown = -20;
        else
            self.actTime.text = string.format(getLanguage("排行结算：", nil, "排行结算：%s"), HelperFunc.GetSurpTimeStr(self.challengeTimeCountDown));
            self.challengeTimeCountDown = self.challengeTimeCountDown - 1;
        end
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M:refreshTopCost()
    if tonumber(self.itemId1) == CurrencyEnum.MONEY then
        self.CoinLb.text = getNumString(logicMgr.ItemManager.getBagNumByTableID(tonumber(self.itemId1)));
    else
        self.CoinLb.text = (logicMgr.ItemManager.getBagNumByTableID(tonumber(self.itemId1)));
    end
    if tonumber(self.itemId2) == CurrencyEnum.MONEY then
        self.CoinLb1.text = getNumString(logicMgr.ItemManager.getBagNumByTableID(tonumber(self.itemId2)));
    else
        self.CoinLb1.text = (logicMgr.ItemManager.getBagNumByTableID(tonumber(self.itemId2)));
    end
end

function _M:refreshCost()
    self:refreshTopCost();
    if self.tableDataCfg == nil then
        return
    end
    local data = decodeJsonStrToTabel(self.tableDataCfg.f_DrawConsume);
    local id = data[1][1];
    local item = logicMgr.ItemManager.getItemConstDatabyModelId(id);
    if item ~= nil then
        self.costIcon1.icon = EnumConst.AtlasPath.ItemAtlas..item.icon;
    end
    local hasNum = logicMgr.ItemManager.getBagNumByTableID(tonumber(id));
    local costNum = tonumber(data[1][2]);
    if hasNum >= costNum then
        self.txtCost1.text = "[color=#FFFFFF]" .. costNum .. "[/color]";
        self.itemName1 = nil;
    else
        self.txtCost1.text = "[color=#FF2A4D]"..costNum.."[/color]";
        self.itemName1 = "";
        if item ~= nil then
            self.itemName1 = item.name;
        end
    end

    id = data[2][1];
    item = logicMgr.ItemManager.getItemConstDatabyModelId(id);
    if item ~= nil then
        self.costIcon2.icon = EnumConst.AtlasPath.ItemAtlas..item.icon;
    end
    hasNum = logicMgr.ItemManager.getBagNumByTableID(tonumber(id));
    costNum = tonumber(data[2][2]);
    if hasNum >= costNum then
        self.itemName2 = nil;
        self.txtCost2.text = "[color=#FFFFFF]" .. costNum .. "[/color]";
    else
        self.txtCost2.text = "[color=#FF2A4D]"..costNum.."[/color]";
        self.itemName2 = "";
        if item ~= nil then
            self.itemName2 = item.name;
        end
    end

    local todayTurnCount = tonumber(self.turntableInfo.todayTurnCount);
    local dailyFreeTimes = tonumber(self.tableDataCfg.f_DailyFreeTimes);
    if todayTurnCount < dailyFreeTimes then
        self.txtFree.text = string.format(getLanguage("免费召唤 %s次", nil, "免费召唤 %s次"), dailyFreeTimes - todayTurnCount);
        self.freeCtrl.selectedIndex = 1;
    else
        self.freeCtrl.selectedIndex = 0;
    end
    local serverRankInfo = logicMgr.ActiveManager.GetTurntableRankInfo(self.activeId,1);
    local noRank = getLanguage("NotInRank");
    local serverName = getLanguage("本服排行：", nil, "本服排行：%s");
    local serverName2 = getLanguage("跨服排行：", nil, "跨服排行：%s");
    local scoreName = getLanguage("当前积分：", nil, "当前积分：%s");
    self.score.text = string.format(scoreName, self.turntableInfo.score);
    if serverRankInfo == nil then
        self.rankTips1.text = string.format(serverName, noRank);
    else
        if serverRankInfo.selfRank > 50 or serverRankInfo.selfRank < 0 then
            self.rankTips1.text = string.format(serverName, noRank);
        else
            self.rankTips1.text = string.format(serverName,serverRankInfo.selfRank);
        end
    end
    serverRankInfo = logicMgr.ActiveManager.GetTurntableRankInfo(self.activeId,2);
    if serverRankInfo == nil then
        self.rankTips2.text = string.format(serverName2, noRank);
    else
        if serverRankInfo.selfRank > 50 or serverRankInfo.selfRank < 0 then
            self.rankTips2.text = string.format(serverName2, noRank);
        else
            self.rankTips2.text = string.format(serverName2, serverRankInfo.selfRank);
        end
    end
    local maxNum = tonumber(self.tableDataCfg.f_HeroSelect[2]);
    item = logicMgr.ItemManager.getItemConstDatabyModelId(self.tableDataCfg.f_HeroSelect[1]);
    local resetNum = maxNum - tonumber(self.turntableInfo.insureCount);
    if resetNum < 0 then
        resetNum = 0;
    end
    --self.showTips.text = string.format(getLanguage("ActivityDesc1900101", nil, "召唤%s/%s次必得%s"), resetNum,maxNum, item.name);
    self.showTips.text = getLanguage("ActivityTips19001010");
end

function _M:onClickBtn(index)
    if self.selectIndex == index then
        self.selectIndex = index;
        return;
    end
    if index == 1 or index == 7 then
        self.selectIndex = index;
        self:refreshCost();
        self.name.text = getLanguage("ActivityTips190010"..self.selectIndex);
        return;
    end
    self.selectIndex = index;
    self.name.text = getLanguage("ActivityTips190010"..self.selectIndex);
    if self.selectIndex == 2 then
        -- 充值
        if self.rechargeItem == nil then
            self.rechargeItem = RechargeItem--CtrlManager.GetCtrl(PanelNames.RechargeItemPath);
            self.rechargeItem.initData(self.activeId, self.totalRecharge, self.challengeTimeCountDown);
        else
            self.rechargeItem.updateData(self.challengeTimeCountDown);
        end
    elseif self.selectIndex == 3 or self.selectIndex == 6 then
        -- 任务
        local taskType = self.selectIndex == 3 and 1 or 2;
        if self.taskItem == nil then
            self.taskItem = TaskItem--CtrlManager.GetCtrl(PanelNames.TaskItemPath);
            self.taskItem.initData(self.activeId, self.luckyGuyTask, self.challengeTimeCountDown, taskType);
        else
            self.taskItem.updateData(self.challengeTimeCountDown, taskType);
        end
    else
        -- 排行榜
        local rank = self.selectIndex == 4 and 1 or 2;
        if self.rankItem == nil then
            self.rankItem = RankItem--CtrlManager.GetCtrl(PanelNames.RankItemPath);
            self.rankItem.initData(self.activeId, self.luckyGuyRank,rank, self.challengeTimeCountDown);
        else
            self.rankItem.ReqRankList(rank, self.challengeTimeCountDown)
        end
        local openState = logicMgr.ActiveManager.getActiveOpenStatus(self.activeId, 1);
        if openState ~= nil and openState then
            self.rankRedCtrl.selectedIndex = 0;
            logicMgr.ActiveManager.updateActiveOpenStatus(self.activeId, 1);
        end
    end
end

-- 隐藏
function _M:OnDisable()

end

function _M:OnClose()
    logicMgr.HeroManager.setGetNewHeroShow();
    self:OnBack();
end

function _M:DestroyTimer()
    if self.updateTimer ~= nil then
        self.updateTimer:Stop()
        self.updateTimer = nil
    end
end

function _M:DestroyRewardTimer()
    if self.rewardTimerId ~= nil then
        utimer.remove(self.rewardTimerId);
        self.rewardTimerId = nil;
    end
end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    self.hasInit = false
    if self.rechargeItem then
        self.rechargeItem.OnDestroy()
    end
    if self.taskItem then
        self.taskItem.OnDestroy()
    end
    if self.rankItem then
        self.rankItem.OnDestroy();
    end
    if self.RoleLihui~=nil then
        destroy(self.RoleLihui);
        self.RoleLihui = nil;
    end
    if self.drawWrapper then
        self.drawWrapper:Dispose();
        self.drawWrapper = nil;
    end
    if self.effectGo~=nil then
        destroy(self.effectGo);
        self.effectGo = nil;
    end
    if self.effWrapper then
        self.effWrapper:Dispose();
        self.effWrapper = nil;
    end
    if self.effectGo1~=nil then
        destroy(self.effectGo1);
        self.effectGo1 = nil;
    end
    if self.effWrapper1 then
        self.effWrapper1:Dispose();
        self.effWrapper1 = nil;
    end
    self.rechargeItem = nil;
    self.taskItem = nil;
    self.rankItem = nil;
    self:DestroyTimer();
    self:DestroyRewardTimer();
    if self.idleTimer then
        self.idleTimer:Stop();
    end
    self.idleTimer = nil;
    self.selectIndex = 1;
    self.curRotation = 0;
    self.preRotation = 0;
    self.acSpeed = 3;
    self.acTime = 20;
    self.acDis = 0;
    self.speed = 0;
    self.speedTime = 0;
    self.reSpeed = 1;
    self.reTime = 60;
    self.reDis = 0;
    self.reSpeedTime = 0;
    self.reSpeedDic = 0;
    self.spTime = 0;
    self.curRewardIndex = 1;
    self.spCount = 0;
    self.rewardRotation = 45;
    self.spineAnim = nil;
    self.particleSystem = nil;
    self.hasInitRewardItem = false;
    self.activityType = 0;
    self.resetRewardCost = 0;
    self.isClick = false;
    self.drawType = 0;
    self.lastDrawType = 0;
end

return _M;